
function getCate(business_from_or_to,business,stat_date,selecotr,url,plat){
	$.ajax({
	    url: '/dashboard/netflow/ajax/getcate/'+url,
	    type: 'POST',
	    async: true,
	    data: {
	      "business_from_or_to":business_from_or_to,
	      "business": business,
	      "stat_date": stat_date,
	      "plat":plat
	    },
	    dataType: 'json',
	    
	    success: function(data, textStatus) {
	    	 $(selecotr).empty();
             var option = '<option value="all">全部</option>';
             $.each(data.cateList,function(index,value){
            	 if(value=='all'||value=="-"){
            		 return true;
            	 }
            	 option += '<option value="' +value+ '">' +value + '</option>';
             });
	        $(selecotr).append(option);
	    },
	    error: function() {
	      alert('error!');
	    }
	  });
}

//切换平台
$("#plat").change(function() {
	  
	  var plat = $("#plat").val();
	  $.ajax({
		    url: '/dashboard/netflow/ajax/setMaxDate',
		    type: 'POST',
		    async: true,
		    data: {
		      "plat":plat,
		      "option":"trafficflow"
		    },
		    dataType: 'json',
		    
		    success: function(data, textStatus) {
		    	 
		    	 $("#stat_date").val(data.stat_date);
		    	 $('#stat_date').datepicker('update');
		    },
		    error: function() {
		      alert('error!');
		    }
		  });
});

$("#serviceLineF").change(function() {

  var business_from = $(this).val();
  var stat_date = $('#stat_date').val();
  var plat = $("#plat").val();
  getCate("business_type_from",business_from,stat_date,"#FirstClassF","trafficflow",plat);
});

$("#serviceLineT").change(function() {
	var business_to = $(this).val();
	var stat_date = $('#stat_date').val();
	var plat = $("#plat").val();
	getCate("business_type_to",business_to,stat_date,"#FirstClassT","trafficflow",plat);
});

$("#searchBtn").click(function() {
  show();
});

function show() {
  var business_from = $('#serviceLineF').val();
  var business_to = $('#serviceLineT').val();
  var cate1_from = $('#FirstClassF').val();
  var cate1_to = $('#FirstClassT').val();
  var page_from = $('#page_type_from').get(0).value;
  var page_to = $('#page_type_to').get(0).value;
  var stat_date = $('#stat_date').val();
  var platform = $('#platform').val();
  var plat = $("#plat").val();
  
  var stat_date = $('#stat_date').val();
  $.ajax({
    url: '/dashboard/netflow/ajax/trafficFlow',
    type: 'POST',
    async: true,
    data: {
      "business_from": business_from,
      "business_to": business_to,
      "cate1_from": cate1_from,
      "cate1_to": cate1_to,
      "page_from": page_from,
      "page_to": page_to,
      "stat_date": stat_date,
      "platform": platform,
       "plat":plat
    },
    dataType: 'json',
    success: function(data, textStatus) {

      d3.select("#chart svg").remove();
      showIamge(data);
      if(data.length==0){
    	  alert("该条件下暂无数据！");
      }
    },
    error: function() {
      alert('error!');
    }
  });
}

$(function() {
  show();
});

function showIamge(data) {

  var setW = $('#chartMain').width() - 70;
  var margin = {
      top: 1,
      right: 1,
      bottom: 6,
      left: 1
    },
    width = setW - margin.left - margin.right - 300, // was 960
    //height = 1500 - margin.top - margin.bottom; // was 500
    height = 550; // UBS Example
    sumVal=0  // 数据总和
  var formatNumber = d3.format(",.0f"),
    format = function(d) {
      return formatNumber(d);
    },
    color = d3.scale.category20();

  var svg = d3.select("#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var sankey = d3.sankey()
    .nodeWidth(100) // was 15
    .nodePadding(15) // was 10
    .size([width, height]);

  var path = sankey.link();

  d3.json("", function(energy) {
    colors = {
      "home": "#5687d1",
      "index": "#7b615c",
      "list": "#de783b",
      "detail": "#6ab975",
      "qy_detail": "#a173d1",
      "post": "#333333",
      "jianli_detail": "#0066cc",
      "vip": "#cc0033",
      "my": "#EAD85A",
      "others": "#003399",
      "end": "#bbbbbb",
      "empty": "#F98CC5",
      "login": "#EAAE5A",
      "deliver": "#109508",
      "other_biz": "#CB67F3",
      "jump_page": '#e7e7eb',
      "land_page": '#e7e7eb',
      "quit_page": '#e7e7eb'
    };
    energy = test();
    sankey
      .nodes(energy.nodes)
      .links(energy.links)
      .layout(32); // what is this? iterations

    var link = svg.append("g").selectAll(".link")
      .data(energy.links)
      .enter().append("path")
      .attr("class", "link")
      .attr("d", path)
      .style("stroke-width", function(d) {
        return Math.max(1, d.dy);
      })
      // .style("stroke", function(d) { return d.source.color = color(d.source.name.replace(/ .*/, "")); })
      .style("stroke", function(d) {
        return d.source.color = colors[d.source.name];
      })
      .sort(function(a, b) {
        return b.dy - a.dy;
      });

    link.append("title")
    //   .text(function(d) {
    //     return d.source.name + " → " + d.target.name + "\n" + format(d.value);
    //   });
    .text(function(d) {
      return d.source.name + " → " + d.target.name + "\n" + format(d.value) + "\n" + (d.value/d.s_sum*100).toFixed(2) + "%";
    });
    // title is an SVG standard way of providing tooltips, up to the browser how to render this, so changing the style is tricky

    var node = svg.append("g").selectAll(".node")
      .data(energy.nodes)
      .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) {
        return "translate(" + d.x + "," + d.y + ")";
      })
      .on('mouseover', mouseoverFun)
      .on('mouseout', mouseoutFun)
      .call(d3.behavior.drag()
        .origin(function(d) {
          return d;
        })
        .on("dragstart", function() {
          this.parentNode.appendChild(this);
        })
        .on("drag", dragmove));

    // 鼠标移入node节点时相应连线高亮
    function mouseoverFun() {
      var nodeTarget, nodeSource;
      d3.select(this).attr('target', function(d) {
        nodeTarget = d.target; // 当前节点的target值
        nodeSource = d.source; // 当前节点的source值
        if (nodeTarget != undefined && nodeTarget != null) { // 如果当前节点是target节点
          link.attr("class", function(d) {
            if (d.target.name == nodeTarget) { // 绘制对应连线
              return 'link linkHover';
            } else {
              return 'link';
            }
          });
        } else if (nodeSource != undefined && nodeSource != null) { //如果当前节点是source节点
          link.attr("class", function(d) {
            if (d.source.name == nodeSource) { // 绘制对应连线
              return 'link linkHover';
            } else {
              return 'link';
            }
          });
        }
      })
    }

    // 鼠标移出node节点时还原样式
    function mouseoutFun() {
      link.attr("class", "link");
    }
    node.append("rect")
      .attr("width", sankey.nodeWidth())
      .attr("height", function(d) {
        return d.dy;
      })
      // .style("fill", function(d) { return d.color = color(d.name.replace(/ .*/, "")); })
      .style("fill", function(d) {
        return d.color = colors[d.name];
      })
      // .style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
      .append("title")
      // .text(function(d) {
      //   return d.name + "\n" + format(d.value);
      // });
      .text(function(d) {
        return d.name + "\n" + format(d.value) + "\n" + (d.value/sumVal*100).toFixed(2) + "%";
      });

    node.append("text")
      .attr("text-anchor", "middle")
      .attr("y", function(d) {
        return d.dy / 2
      })
      .attr("x", sankey.nodeWidth() / 2)
      .attr("dy", ".35em")
      .text(function(d) {
        return d.name;
      })
      .filter(function(d) {
        return d.x < width / 2;
      });

    function dragmove(d) {
      d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
      sankey.relayout();
      link.attr("d", path);
    }

    // 数图转化
    function test() {
      // 模拟数据
      var testData1 = [
        ['vip', 'list', 49978],
        ['empty', 'post', 7458],
        ['deliver', 'jump_page', 17054],
        ['empty', 'list', 410834],
        ['qy_detail', 'qy_detail', 46461],
        ['vip', 'others', 99503],
        ['vip', 'vip', 6331],
        ['all', 'post', 7408],
        ['deliver', 'jump_page', 1720],
        ['empty', 'list', 54834]
      ]

      var testData = data;

      //var s = "a-b-3,a-a-2,b-a-5,b-b-6"
      var sourceMap = {}
      var targetMap = {}
      var count = 0;
      // var  arr = s.split(",")
      var nodes = []
      for (var i = 0; i < testData.length; i++) {
        var kk = testData[i];
        var ss = kk[i + ""].split(",");
        // var ss = testData[i];
        var source = ss[0]
        var target = ss[1]
        if (sourceMap[source] == null && source != 'all' && target != 'all') {
          // sourceMap[source] = count++;
          sourceMap[source]={
            count: count++,
            s_sum: null // source的value和
          }
          var node = new Object();
          node.name = source;
          node.source = source;
          nodes.push(node)
        };

        if (targetMap[target] == null && target != 'all' && source != 'all') {
          targetMap[target] = count++;
          var node = new Object();
          //console.log(target)
          node.name = target;
          node.target = target;
          nodes.push(node)
        };
      };

      var links = []
      for (var i = 0; i < testData.length; i++) {
          var kk = testData[i];
          var ss = kk[i + ""].split(",");
          var source = ss[0];
          var target = ss[1];
          var value = parseInt(ss[2])
          if (source == 'all' || target == 'all') {
            continue
          };
          sumVal += value;
          sourceMap[source].s_sum += value;
      }
      for (var i = 0; i < testData.length; i++) {
        var kk = testData[i];
        var ss = kk[i + ""].split(",");
        // var ss = testData[i];
        var source = ss[0]
        var target = ss[1]
        if (source == 'all' || target == 'all') {
          continue
        };
        var value = parseInt(ss[2])

        var link = new Object()
        link.source = sourceMap[source].count
        link.target = targetMap[target]
        link.value = value
        link.s_sum = sourceMap[source].s_sum;
        links.push(link)
      }

      var json = new Object()
      json.nodes = nodes;
      json.links = links;
      return json
    }
  });
}